import router from '@/router';
import axios from 'axios'
import { Message } from 'element-ui';

export const http = axios.create({
    baseURL: process.env.VUE_APP_BASE_API,
})

http.interceptors.request.use(
    (config) => {
        const access_token = localStorage.getItem('token')
        config.headers.token = access_token
        return config;
    },
    (err) => {
        console.error(err);
    }
)

http.interceptors.response.use(
    (res) => {
        if ([401, 402].includes(res.data.code)) {
            Message.error("登录过期,请重新登录！");
            try {
                setTimeout(() => {
                    router.push({
                        path: '/',
                    })
                }, 1500);
                localStorage.removeItem('token')
            } catch (e) {
                console.log(e.message);
            }
        }
        // if (res.data.code == 500 || res.data.code == 501) {
        //     Message.error(res.msg);
        // }
        return res.data
    },
    (err) => {
        Message.error("出小差了");
        console.error(err);
        return false;
    }
)